import MenuRole from '@/components/menuRole';
import TreeSide from '@/components/TreeSide';
import { getCategoryList } from '@/services/category';
import { getCatGroupPerList, updateCatGroupPerList } from '@/services/permission';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, Col, message, Row } from 'antd';
import React, { useEffect, useState } from 'react';
const Index: React.FC = (props) => {
  //list
  const [dataList, setDataList] = useState([]);

  //select
  const [selectedTreeData, setSelectedTreeData] = useState([]);
  //tree
  const [treeData, setTreeData] = useState([]);
  useEffect(() => {
    getCategory();
  }, []);

  //更改树结构
  const changeTreeData = (data) => {
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      element.key = element.id;
      element.title = element.name;
      if (element.children && element.children.length > 0) {
        changeTreeData(element.children);
      }
    }
    return data;
  };
  //查询分类
  const getCategory = () => {
    const params = {
      type: 'topic',
    };
    //获取组list
    getCategoryList(params).then(async (res) => {
      const data = changeTreeData(res.data);
      setTreeData(data);
    });
  };

  useEffect(() => {
    getRoleList();
  }, [selectedTreeData]);

  const getRoleList = async () => {
    if (selectedTreeData.length == 0 || selectedTreeData == undefined) {
      setDataList([]);
    } else {
      const params = {
        catId: selectedTreeData,
      };
      const res = await getCatGroupPerList(params);
      if (res.code == '0') {
        setDataList(res.data);
      }
    }
  };

  const onSubmit = async () => {
    const params = {
      catId: selectedTreeData,
      groupPerList: dataList,
    };
    console.log(params);
    const res = await updateCatGroupPerList(params);
    if (res.code == '0') {
      message.success('保存成功！');
    } else {
      message.error('保存失败！');
    }
  };
  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <Card title="资讯中心目录权限">
        <Row gutter={[16, { xs: 8, sm: 16, md: 24, lg: 32 }]}>
          <Col span={4}>
            <TreeSide defaultData={treeData} setSelectedTreeData={setSelectedTreeData} />
          </Col>
          <Col span={20}>
            <div key={new Date().getTime()}>
              {dataList.map((item) => {
                return (
                  <MenuRole
                    groupItem={item}
                    key={item.groupId}
                    dataList={dataList}
                    setDataList={setDataList}
                  />
                );
              })}
            </div>
          </Col>
        </Row>
        {dataList.length > 0 ? (
          <Button type="primary" style={{ marginLeft: '50%', marginTop: 20 }} onClick={onSubmit}>
            保存
          </Button>
        ) : null}
      </Card>
    </PageContainer>
  );
};

export default Index;
